/* eslint-disable no-unused-expressions */
import React, { useContext, useState, useEffect, useRef } from 'react';
import { Table, Input, Button, Popconfirm, Form, Checkbox, message, Select } from 'antd';
import { queryStore, getDictionary } from '../service';
import { ConsoleSqlOutlined } from '@ant-design/icons';
const EditableContext = React.createContext(null);

const EditableRow = ({ index, ...props }) => {
  const [form] = Form.useForm();
  return (
    <Form form={form} component={false}>
      <EditableContext.Provider value={form}>
        <tr {...props} />
      </EditableContext.Provider>
    </Form>
  );
};

const EditableCell = ({
  title,
  editable,
  children,
  dataIndex,
  record,
  handleSave,
  ...restProps
}) => {
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  const form = useContext(EditableContext);
  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
    form.setFieldsValue({
      [dataIndex]: record[dataIndex],
    });
  };

  const save = async () => {
    try {
      const values = await form.validateFields();
      toggleEdit();
      handleSave({ ...record, ...values });
    } catch (errInfo) {
      console.error('Save failed:', errInfo);
    }
  };

  let childNode = children;

  if (editable) {
    childNode = editing ? (
      <Form.Item
        style={{
          margin: 0,
        }}
        name={dataIndex}
      >
        <Input ref={inputRef} onPressEnter={save} onBlur={save} />
      </Form.Item>
    ) : (
      <div
        className="editable-cell-value-wrap"
        style={{
          paddingRight: 24,
        }}
        onClick={toggleEdit}
      >
        {children}
      </div>
    );
  }

  return <td {...restProps}>{childNode}</td>;
};

export default class EditableTable extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      num: '',
      numState: null,
      defalutData: [],
      dataSource: [],
      checkFocus: false,
      searchName: '',
      person: '',
      cityState: true,
      areaState: true,
      show: true,
      count: 2,
      defaultKey: [],
      loading:false
    };
    // this.CommissionColumns = [
    //   {
    //     title: '名称',
    //     dataIndex: 'name',
    //   },
    //   {
    //     title: '联系人',
    //     dataIndex: 'contacts',
    //   },
    //   {
    //     title: '库存',
    //     dataIndex: 'stock',
    //     editable: true,
    //     width: 100,
    //     render: (_, record) => {
    //       return <span>{_ ? _ : '--'}</span>;
    //     },
    //   },
    // ];
    this.columns = [
      {
        title: '名称',
        dataIndex: 'name',
      },
      {
        title: '联系人',
        dataIndex: 'contacts',
      },
    ];
  }

  handleSave = (row, payload) => {
    if (payload) {
      let list = this.findNode(row, payload);
      this.setState({ dataSource: list });
      this.props.childrenCommission(row);
    } else {
      let list = this.findNode(
        row,
        this.state.dataSource.length > 0 ? this.state.dataSource : this.props.dataSource,
      );
      const data = JSON.parse(JSON.stringify(this.state.defalutData)).concat(row);
      this.setState({ dataSource: list, defalutData: data });
      this.props.childrenCommission(row);
    }
  };

  findNode = (row, storeList) => {
    let list = [];
    storeList.forEach((obj) => {
      if (obj.id == row.id) {
        obj.stock = row.stock;
      } else {
        if (obj.children) {
          let children = this.findNode(row, obj.children);
          obj.children = children;
        }
      }
      list.push(obj);
    });
    return list;
  };
  handleSearchName = (e) => {
    this.setState({
      searchName: e.target.value,
    });
  };
  handleSearchMan = (e) => {
    this.setState({
      person: e.target.value,
    });
  };
  handleSetCommission = (data) => {
    // const { dataSource } = this.props;
    const { defalutData } = this.state;

    data.map((item) => {
      defalutData.map((item_) => {
        if (item.id === item_.storeId) {
          item.stock = item_.stock;
        }
      });
      if (item.children) {
        this.handleSetCommission(item.children);
      }
    });
    return data;
  };
  handleSearch = () => {
    // this.props.searchState();
    const { searchName, person } = this.state;
    this.setState({
      loading:true
    });

    queryStore({
      name: searchName,
      contacts: person,
      parent: true,
    }).then(async (res) => {
      const { data } = res;
      this.setState({
        loading:false
      });
      if (data && data.length > 0) {
        await this.handleSetCommission(data);
        let newExpandedKeys = [];
        const handleShowkey = (payload) => {
          payload.map((item, index) => {
            newExpandedKeys.push(item.id);
            if (item.children) {
              return handleShowkey(item.children);
            }
          });
          return newExpandedKeys;
        };
        const list = handleShowkey(data);
        this.setState({
          dataSource: data,
          defaultKey: list,
        });
      } else if (data.length === 0) {
        message.info('暂无查询的内容！');
      }
    });
  };

  render() {
    const { province, city, area, cityState, areaState, show, defaultKey,loading } = this.state;
    const { handleChildren, dataSource, onSelect, onSelectAll, CommissionState,onChange } = this.props;
    let newSource = this.state.dataSource.length > 0 ? this.state.dataSource : dataSource;

    const rowSelection = {
      newSource,
      selectedRowKeys: handleChildren,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
      onChange:onChange
    };
    const components = {
      body: {
        row: EditableRow,
        cell: EditableCell,
      },
    };
    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col;
      }

      return {
        ...col,
        onCell: (record) => ({
          record,
          editable: col.editable,
          dataIndex: col.dataIndex,
          title: col.title,
          handleSave: this.handleSave,
        }),
      };
    });
    // const CommissionColumns = this.CommissionColumns.map((col) => {
    //   if (!col.editable) {
    //     return col;
    //   }

    //   return {
    //     ...col,
    //     onCell: (record) => ({
    //       record,
    //       editable: col.editable,
    //       dataIndex: col.dataIndex,
    //       title: col.title,
    //       handleSave: this.handleSave,
    //     }),
    //   };
    // });

    return (
      <div className="edit_Table">
        <div className="searchStore">
          <div className="search_div">
            <span>店铺名称:</span>
            <Input
              style={{ width: '60%' }}
              onChange={this.handleSearchName}
              placeholder="店铺名称"
            />
          </div>
          <div className="search_div">
            <span>联系人:</span>
            <Input style={{ width: '60%' }} onChange={this.handleSearchMan} placeholder="联系人" />
          </div>

          <Button type="primary" onClick={this.handleSearch}>
            查询
          </Button>
        </div>
        <Table
          components={components}
          rowClassName={() => 'editable-row'}
          bordered
          rowKey={(record) => record.id}
          loading={loading}
          expandable={{
            expandedRowKeys: defaultKey,
            onExpandedRowsChange: (e) => {
              this.setState({
                defaultKey: e,
              });
            },
          }}
          dataSource={this.state.dataSource.length > 0 ? this.state.dataSource : dataSource}
          onExpand={(e, payload) => {
            const rowKey = this.state.dataSource.findIndex((item) => payload.key === item.key);
            return e
              ? this.setState(
                  () => {},
                  () => {
                    this.setState({
                      num: rowKey,
                      numState: e,
                    });
                  },
                )
              : null;
          }}
          columns={columns}
          rowSelection={rowSelection}
        />
      </div>
    );
  }
}
